import axios from 'axios'
import type { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'

// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: 'http://localhost:8000',  // 后端 API 地址
  timeout: 15000,
  withCredentials: true, // 允许携带 cookie
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 可以在这里添加 token
    const token = localStorage.getItem('token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    
    // 直接返回响应数据，让组件自己处理错误
    return res
  },
  (error) => {
    console.error('响应错误:', error)
    
    if (error.response) {
      const { status, data } = error.response
      
      let errorMessage = '请求失败'
      
      switch (status) {
        case 401:
          errorMessage = data?.message || '用户名或密码错误'
          // 只有在非登录页面且确实是未授权的情况下才跳转
          if (window.location.pathname !== '/login' && !data?.message?.includes('密码')) {
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            window.location.href = '/login'
          }
          break
        case 403:
          errorMessage = data?.message || '没有权限'
          break
        case 404:
          errorMessage = data?.message || '请求的资源不存在'
          break
        case 500:
          errorMessage = data?.message || '服务器错误'
          break
        default:
          errorMessage = data?.message || '请求失败'
      }
      
      // 创建包含详细信息的错误对象
      const err: any = new Error(errorMessage)
      err.status = status
      err.data = data
      return Promise.reject(err)
    } else if (error.request) {
      const err: any = new Error('网络错误，请检查网络连接')
      return Promise.reject(err)
    }
    
    return Promise.reject(error)
  }
)

export default service